from flask import Blueprint, request, jsonify
from .Cmod import *
from .Cmod_user import *
from .Cmod_express import *

blue_fav = Blueprint('favorite', __name__)


# 查询用户是否收藏该项目
@blue_fav.route('/api/search/favorite', methods=['POST', 'GET'])
def query_type_collect_now():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    data = request.get_json()
    object_id = data.get('object_id')
    object_type = data.get('object_type')
    user_id = data.get('user_id')
    collect_now = Favorite.query.filter_by(favorite_user=user_id,
                                           favorite_object=object_id,
                                           favorite_type=object_type).first()
    if collect_now is not None:
        return {'message': '已收藏'}, 200
    else:
        return {'message': '未收藏'}, 200


# 用户增删收藏,增加默认放入默认收藏夹中
@blue_fav.route('/api/add/collect', methods=['POST', 'GET'])
def collect():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    data = request.get_json()
    favorite_user = data.get('id')
    favorite_object = data.get('object_id')
    object_type = data.get('object_type')
    user_type = data.get('type')
    if user_type == "add":
        favorite_now = Favorite(
            favorite_user=favorite_user,
            favorite_object=favorite_object,
            favorite_type=object_type
        )
        db.session.add(favorite_now)
        db.session.commit()
        return {'message': '收藏成功'}, 200

    elif user_type == "less":
        favorite_now = Favorite.query.filter_by(favorite_user=favorite_user,
                                                favorite_object=favorite_object,
                                                favorite_type=object_type).first()
        favoriterelation_now = FavoriteRelation.query.filter_by(relation_favorite_id=favorite_now.favorite_id).all()
        if favoriterelation_now is not None:
            for favr in favoriterelation_now:
                db.session.delete(favr)
        db.session.delete(favorite_now)
        db.session.commit()
        return {'message': '取消收藏成功'}, 200

    else:
        return {'message': '未识别的type字符串'}, 400


# 将已经收藏的东西添加或者移出收藏夹
@blue_fav.route('/api/move/favorite_bag', methods=['POST', 'GET'])
def move_favorite_bag():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    data = request.get_json()
    favorite_user = data.get('user_id')
    favorite_name = data.get('bag_name')
    favorite_id_list = data.get('favorite_id_list')
    user_type = data.get('type')

    bag_id = get_favoritebag_id(favorite_name, favorite_user)
    if user_type == "add":
        for favorite_id in favorite_id_list:
            frt = FavoriteRelation(
                relation_favorite_bag_id=bag_id,
                relation_favorite_id=favorite_id,
                relation_favorite_user=favorite_user
            )
            db.session.add(frt)
        db.session.commit()
    elif user_type == "less":
        for favorite_id in favorite_id_list:
            frt = FavoriteRelation.query.filter_by(relation_favorite_bag_id=bag_id,
                                                   relation_favorite_id=favorite_id,
                                                   relation_favorite_user=favorite_user).first()
            db.session.delete(frt)
        db.session.commit()
    else:
        return {'message': '未识别的type字符串'}, 400
    return {'message': '操作成功'}, 200


# 创建或者删除收藏夹,同一用户不能存在同名收藏夹
@blue_fav.route('/api/create/favorite/bag', methods=['POST', 'GET'])
def create_favorite_bag():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    data = request.get_json()
    user_id = data.get('user_id')
    favoritebag_name = data.get('bag_name')
    type_now = data.get('type')
    if type_now == 'add':
        if is_exist_folder(user_id, favoritebag_name):
            return {'message': '已存在该收藏夹'}, 201
        favoritebag_now = Favoritebag(
            favoritebag_user=user_id,
            favoritebag_name=favoritebag_name
        )
        db.session.add(favoritebag_now)
        db.session.commit()
        return {'message': '创建收藏夹成功'}, 200
    elif type_now == 'less':
        if is_exist_folder(user_id, favoritebag_name):

            favoritebag_now = Favoritebag.query.filter_by(favoritebag_user=user_id,
                                                          favoritebag_name=favoritebag_name).first()
            # 还得清理与该收藏夹有关系的项目
            relafav = FavoriteRelation.query.filter_by(
                relation_favorite_bag_id=favoritebag_now.favoritebag_id).all()
            for relafav_now in relafav:
                db.session.delete(relafav_now)
            db.session.delete(favoritebag_now)
            db.session.commit()
            return {'message': '删除收藏夹成功'}, 200
        else:
            return {'message': '收藏夹不存在'}, 201
    else:
        return {'message': '未识别的type字符串'}, 400


# 渲染用户收藏夹
@blue_fav.route('/api/render/favorite/bag', methods=['POST', 'GET'])
def render_favorite_bag():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    data = request.get_json()
    user_id = data.get('id')
    favoritebags = Favoritebag.query.filter_by(favoritebag_user=user_id).all()
    favorite_now = Favorite.query.filter_by(favorite_user=user_id).all()
    favorites_without_relation = (
        Favorite.query.outerjoin(FavoriteRelation,
                                 Favorite.favorite_id == FavoriteRelation.relation_favorite_id)  # 左外连接
            .filter(FavoriteRelation.relation_id is None)  # 筛选出FavoriteRelation中没有对应的记录
            .all()
    )
    favorite_id_list1 = [favorite.favorite_id
                         for favorite in favorites_without_relation]
    fnl1 = {
        'bag_id': '无',
        'bag_name': "默认文件夹",
        'favorite_id_list': favorite_id_list1
    }
    favorite_name_list_now = [fnl1]
    for favoritebag in favoritebags:
        favorite_id_now = \
            FavoriteRelation.query. \
                filter_by(relation_favorite_bag_id=favoritebag.favoritebag_id).all()
        favorite_id_list = [relation.relation_favorite_id
                            for relation in favorite_id_now]
        fnl = {
            'bag_id': favoritebag.favoritebag_id,
            'bag_name': favoritebag.favoritebag_name,
            'favorite_id_list': favorite_id_list
        }
        favorite_name_list_now.append(fnl)
    fav_list_now = []
    for fav_now in favorite_now:
        title_now = search_object_title(fav_now.favorite_object, fav_now.favorite_type)
        list_now = {
            'favorite_id': fav_now.favorite_id,
            'object_id': fav_now.favorite_object,
            'object_type': fav_now.favorite_type,
            'object_title': title_now
        }
        fav_list_now.append(list_now)
    response = {
        'favorite_name_list_now': favorite_name_list_now,
        'fav_list_now': fav_list_now
    }
    return jsonify(response)
